import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mac
 * Date: 2022-10-10
 * Time: 17:16
 */
public class TestHeap {
    public int[] elem;
    int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }

    /**
     * 向下调整
     * @param parent 每棵树的根节点
     * @param len 每棵树调整的结束位置
     */
    public void shiftDown(int parent, int len) {
        int child = 2 * parent + 1;

        //数学公式推导 - 错位相减 - 时间复杂度O(n)
        //1.循环依次修改位置
        while (child < len) {//向下调整一直到根
            if (child + 1 < len && elem[child] < elem[child + 1]){//判断是否已经是叶子结点或者当前堆已经为大根堆
                child++;
            }
            if (elem[parent] < elem[child]){//交换
                int ret = elem[parent];
                elem[parent] = elem[child];
                elem[child] = ret;
            }else{
                break;
            }
            parent = child;//向下调整具体操作
            child = child * 2 + 1;
        }
    }
    public void createHeap(int[] array){
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
        for (int parent = (usedSize - 2) / 2; parent >= 0; parent--) {
            shiftDown(parent,usedSize);
        }
    }

    private void shiftUp(int child){
        int parent = (child - 1) / 2;
        while (parent >= 0){
            if (elem[parent] < elem[child]){
                int ret = elem[parent];
                elem[parent] = elem[child];
                elem[child] = ret;
            }else{
                break;
            }
            child = parent;
            parent = (parent - 1) / 2;
        }
    }

    public void offer(int val){
        if (isFull()){
            elem = Arrays.copyOf(elem, 2 * elem.length);
        }
        elem[usedSize++] = val;
        shiftUp(usedSize - 1);
    }

    public boolean isFull(){
        return usedSize == elem.length;
    }

    public int poll(){
        if (isEmpty()){
            throw new RuntimeException("优先级队列为空！");
        }
        int ret = elem[0];
        elem[0] = elem[usedSize - 1];
        elem[usedSize - 1] = ret;
        usedSize--;
        shiftDown(0,usedSize);

        return ret;
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }
}
